package com.leonardo.persistenceme.testaux;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

import MAR.Core.Field;
import MAR.Core.Reflector;

import com.leonardo.persistenceme.Class2Handler;
import com.leonardo.persistenceme.exceptions.DatabaseOperationException;
import com.leonardo.persistenceme.model.Entity;
import com.leonardo.persistenceme.model.persistancehandlers.PersistenceHandler;
import com.leonardo.persistenceme.utils.VectorUtils;

public class OnlyIntMatter extends PersistenceHandler {

	public void persist(Object obj, DataOutputStream stream) throws IOException {
		if(!(obj instanceof Entity))
			throw new IllegalArgumentException();
		
		stream.writeUTF(obj.getClass().getName());
		
		Reflector reflector = (Reflector) obj;
		Vector fields;
		try {
			fields = reflector.getFields();
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e.getMessage());
		}
		VectorUtils.sortFieldsVector(fields);
		for(int i = 0; i < fields.size(); i++) {
			Field field = (Field) fields.elementAt(i);
			if(!Integer.class.equals(field.getType()))
				continue;
			Object value = field.get(reflector);
			Class2Handler.getHandler(field.getType()).persist(value, stream);
		}
	}

	public Object recover(DataInputStream stream) throws IOException {
		String className = stream.readUTF();
		Reflector obj;
		try {
			obj = (Reflector) Class.forName(className).newInstance();
		} catch (InstantiationException e) {
			throw new RuntimeException("Entity should have default contructor");
		} catch (IllegalAccessException e) {
			throw new RuntimeException("Entity should have default contructor");
		} catch (ClassNotFoundException e) {
			throw new DatabaseOperationException("Try to recover unknow " +
					"class from database");
		}
		Vector fields;
		try {
			fields = obj.getFields();
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e.getMessage());
		}
		VectorUtils.sortFieldsVector(fields);
		for(int i = 0; i < fields.size(); i++) {
			Field field = (Field) fields.elementAt(i);
			if(!Integer.class.equals(field.getType()))
				continue;
			Object value = Class2Handler.getHandler(field.getType()).recover(stream);
			field.set(obj, value);
		}
		return obj;

	}

}
